<template>
  <div>
    <el-tree
      ref="tree"
      :data="perList"
      show-checkbox
      node-key="id"
      :default-checked-keys="permIds"
      :props="defaultProps"
      check-strictly
    />
    <div style="text-align: center; margin-top: 20px">
      <el-button>取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { getRoleDetail } from '@/api/setting'
import arrayToTree from 'array-to-tree'
import { assignPerm } from '@/api/setting'
export default {
  name: '',
  props: {
    roleId: {
      type: String,
      default: () => {}
    }
  },
  data() {
    return {
      permIds: [],
      perList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  computed: {},
  created() {
    this.getPer()
    this.getRight()
  },
  methods: {
    //   获取所有权限点列表
    async getPer() {
      const res = await getPermissionList()
      //   为什么赋值了，前端没有出来数据，记得绑定prop
      // 用工具函数把 平铺的数组转成 树型数据
      this.perList = arrayToTree(res.data, {
        parentProperty: 'pid',
        customID: 'id'
      })

      console.log(this.perList, 999)
    },
    async getRight() {
      const res = await getRoleDetail(this.roleId)
      console.log(res, 222)
      this.permIds = res.data.permIds
    },
    // 确认按钮
    async submit() {
      /*
        步骤分析
        1- 点击按钮获取给角色分配的权限  = 获取复选框中的id值
        2- 封装API
        3- 调用函数
        4- 成功 ，关闭对话框 */
      var perMisIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({
        id: this.roleId,
        permIds: perMisIds
      })
      console.log(res)
      this.$emit('success1')
    }
  }
}
</script>
<style lang="less" scoped></style>
